const express = require("express");
const router = express.Router();
const axios = require("axios");
const https = require("https");
const eae = require("express-async-errors");
const path = require("path");

const dateFns = require("date-fns");
const moment = require("moment");
const rds = require("./rds");
const mui = require("./mui");
const logger = require("./logger");
const tutils = require("./tutils");
const task = require("./task");

// 引入会议数据
const conferenceData = require('./data/conference-data.json');

// 异步函数，用于从数据库查询会员数据
async function fetchMemberByUid(uid) {
    const [rows] = await rds.query(
        `SELECT u.uid, u.status, w.headimgurl as avatar, DATE_FORMAT(FROM_UNIXTIME(u.add_time), '%Y-%m-%d') as add_date,
                u.real_name as name, u.phone,
                u.is_promoter, u.promoter_type, u.level, u.roles,
                u.integral as points,
                u.now_money
            FROM tutem_mall.eb_user u
            LEFT JOIN tutem_mall.eb_wechat_user w ON (u.uid = w.uid)
            WHERE u.uid = ? and status = 1`,
        [uid]
    );
    return rows[0]; // 返回查询结果的第一个行，即会员信息
}

// 定义用户类型和文本描述的对象数组
const userTypes = [
    { value: 0, text: "标准用户" },
    { value: 1, text: "诊疗用户" },
    { value: 2, text: "特殊渠道" },
    { value: 3, text: "图腾员工" },
    { value: 9, text: "系统保留" },
];

// 重写getUserTypeText函数
function getUserTypeText(userType) {
    const userTypeObj = userTypes.find((type) => type.value === userType);
    return userTypeObj ? userTypeObj.text : "未知";
}

// 获取代表微信联系方式
router.get("/contact/:rep", (req, res) => {
    const { rep } = req.params || "DXF";
    const imageUrl = `https://mtx.totemlife.cn/apps/public/REP-${rep}.png`;
    res.setHeader("Content-Type", "image/png"); // 设置响应头
    https
        .get(imageUrl, (response) => {
            response.pipe(res);
        })
        .on("error", (err) => {
            console.error(err);
            res.status(500).send("Internal Server Error");
        });
});

router.get("/follow/:rep", (req, res) => {
    const { rep } = req.params || "REP-DXF";
    const imageUrl = `https://mtx.totemlife.cn/apps/public/${rep}.png`;
    https
        .get(imageUrl, (response) => {
            response.pipe(res);
        })
        .on("error", (err) => {
            console.error(err);
            res.status(500).send("Internal Server Error");
        });
});

// 路由：获取随访调查表详情
router.get("/follow-up-detail/:id", async (req, res) => {
    const { id } = req.params;
    const [rows] = await rds.query("SELECT * FROM eb_follow_up WHERE id = ?", [
        id,
    ]);
    if (rows.length > 0) {
        // 将查询到的数据传递给模板
        res.render("loyalty/follow-up-detail", { followUp: rows[0] });
    } else {
        res.status(404).send("随访问卷未找到");
    }
});

// 快捷路由：显示最近一次随访结果
router.get("/latest-survey", async (req, res) => {
    res.redirect(`https://totemlife.cn/apps/loyalty/survey-results/14784502`);
});

// 创建用于列出问卷结果的路由
router.get("/survey-results/:survey_id", async (req, res) => {
    const { survey_id } = req.params;
    const uid = req.session.totemUID;
    logger.info(`uid# ${uid} access survey ${survey_id} results`);
    try {
        const sql = `select s.id, s.uid, u.goods_list, u.spread_uid as cid, s.survey_id, s.action, date_format(from_unixtime(s.add_time), '%Y-%m-%d %H:%i:%s') as submit_at, s.answers_json, s.answers from tutem_mall.eb_tupal_survey s left join tutem_mall.eb_user u on (s.uid = u.uid) where s.survey_id = '${survey_id}' order by s.id desc`;
        const [surveyResults] = await rds.query(sql);
        //临时处理显示格式化及隐私保护
        for (let i = 0; i < surveyResults.length; i++) {
            surveyResults[i].answers = surveyResults[i].answers
                .replace(/\n/g, "\n<br>")
                .replace(
                    /https:\/\/mall\.totemlife\.cn\/uploads\/survey\//g,
                    ""
                );
        }
        const downloadLink =
            req.session.crmROLE == "crm-admin" ||
            req.session.crmROLE == "crm-gmoffc"
                ? `
            <span><a href="https://totemlife.cn/apps/download-excel?sql=${encodeURIComponent(sql)}&filename=${survey_id}-report.xls"><span class="fas fa-download"></i></a></span>
        `
                : "";

        // 渲染列出抽奖结果的页面，并将数据传递给模板
        res.render("loyalty/survey-results", {
            survey_id,
            surveyResults,
            downloadLink,
        });
    } catch (error) {
        console.error("Error fetching lottery results:", error);
        res.status(500).json({ message: "Internal Server Error" });
    }
});

router.get("/follow-ups", async (req, res) => {
    //sinfo 摘要信息
    let {
        rep = "",
        uid = "",
        cid = "",
        status = "",
        sinfo = "",
        took = "",
        rating = "",
        share = "",
        page = 1,
        limit = 50,
        begin = "2020-12-12",
        end = moment().format("YYYY-MM-DD"),
    } = req.query;

    uid = req.session.totemUID;
    const uidCondition = uid == "" ? "" : ` and f.uid = ${uid} `;
    const cidCondition = cid == "" ? "" : ` and u.spread_uid = ${cid} `;
    const statusCondition = status == "" ? "" : ` and f.status = ${status} `;
    const sinfoCondition = sinfo == "" ? "" : ` and f.summary like '%${sinfo}%' `;
    const tookCondition = took == "" ? "" : ` and f.took_months >= ${took} `;
    const ratingCondition = rating == "" ? "" : ` and f.rating >= ${rating} `;
    const shareCondition = share == "" ? "" : ` and f.can_share = ${share} `;
    const timeCondition = ` and DATE_FORMAT(FROM_UNIXTIME(f.submit_time), '%Y-%m-%d') >= '${begin}' AND DATE_FORMAT(FROM_UNIXTIME(f.submit_time), '%Y-%m-%d') <= '${end}'`;

    const query = `
        SELECT
            f.id, f.uid, f.name, f.status, f.survey_link, f.answer_link, f.rating, f.summary, f.comment, DATE_FORMAT(from_unixtime(f.submit_time),'%Y-%m-%d') as submit_at
        FROM
            tutem_mall.eb_follow_up f
            LEFT JOIN tutem_mall.eb_user u ON ( f.uid = u.uid )
        WHERE
            f.uid > 0 ${timeCondition} ${shareCondition} ${ratingCondition} ${tookCondition} ${sinfoCondition} ${statusCondition} ${uidCondition} ${cidCondition}
        ORDER BY
            f.create_time DESC
    `;

    // 获取总记录数和平均评分
    const [totalRows] = await rds.query(
        `SELECT COUNT(*) as total, FLOOR(avg(rating)*20) as avgR FROM (${query}) AS subquery`
    );

    let { total, avgR } = totalRows[0] ?? { total: 0, avgR: 0 };
    if (total == 0) {
        avgR = 0;
    } //当没有记录时total = 0, 其它为null

    const totalPages = Math.ceil(total / limit);
    const startIndex = (page - 1) * limit;

    // 执行分页查询
    const [rows] = await rds.query(
        query + ` LIMIT ${startIndex}, ${limit}`
    );

    const mRows = rows.map((row) => {
        let {
            id,
            uid,
            name,
            status,
            rating,
            summary,
            survey_link,
            answer_link,
            comment,
            submit_at,
        } = row;

        let briefing = `U#${uid} ${name}<br><small>${comment}</small>`;

        let result = "";
        if (status == 1) {
            // 根据 rating 确定 emoji 图标
            let icon =
                rating === -1
                    ? "😞"
                    : rating === 3
                      ? "🤩"
                      : rating === 2
                        ? "😁"
                        : rating === 1
                          ? "😊"
                          : rating === 0
                            ? "😐"
                            : "";
            // 创建五角星字符串，已评分的星号用金色星星表示，未评分的用灰色星星表示
            let stars = "";
            for (let i = -1; i <= rating; i++) {
                stars += "★ "; // 金色星星
            }
            for (let i = rating; i < 3; i++) {
                stars += "☆ "; // 灰色星星
            }

            result += "<small>";
            result =
                rating < -1
                    ? `${icon} ${stars} 未评价`
                    : rating === -1
                      ? `${icon} ${stars}  无作用`
                      : rating === 0
                        ? `${icon} ${stars}  不好说`
                        : rating === 1
                          ? `${icon} ${stars}  有作用`
                          : rating === 2
                            ? `${icon} ${stars}  很有用`
                            : rating === 3
                              ? `${icon} ${stars}  已治愈`
                              : `<br> 无评价`;
            result += "<br>" + summary.substr(0, 15) + "...";
            result += "</small>";
        } else {
            result = `综合评价：尚未提交<br> N/A`;
        }

        result +=
            status === 0
                ? `<br> 📝 待提交<br><small><a href='${survey_link}'>填写问卷</a></small>`
                : status === 1
                  ? `<br> ✅ 已完成<br><small><a href='${answer_link}'>查看结果</a></small>`
                  : status === 9
                    ? `<br> 🚫 已截收<br><small>问卷超期`
                    : `❗ 无状态<br>联系客服</small>`;

        const mRow = { id, briefing, result };
        return mRow;
    });

    const fields = ["序号", "说明", "结果"]; //HBS中可用可不用

    const params = req.query;
    delete params.page; //删除req.query中的page参数以便后面增加
    const link = `/apps/loyalty/follow-ups?${new URLSearchParams(params).toString()}`;
    const paginator = mui.generatePaginator(3, totalPages, page, link);

    const title = `随访列表`;
    const excerpt = `随访总数${total} 平均评价${avgR}`;
    const description = `[${begin},${end}] 共${total}记录 P${page}/${totalPages}<br>筛选条件： [U#${uid}] [C#${cid}] [状态${status}] [评价${rating}] [公开${share}] [内容]${sinfo}`;

    res.render("loyalty/follow-ups", {
        title,
        excerpt,
        description,
        fields: fields,
        rows,
        mRows,
        paginator,
        begin,
        end,
        uid,
        cid,
        status,
        sinfo,
        took,
        rating,
        share,
    });
});

router.get("/", async (req, res) => {
    // 获取会员信息
    const totemUID = req.session.totemUID;
    const member = await fetchMemberByUid(totemUID);

    if (!member) return res.status(404).json({ message: "会员不存在" });
    // 渲染会员中心页面，并将会员信息传递给模板
    res.render("loyalty/home.hbs", {
        avatar: member.avatar || "https://totemlife.cn/apps/default-image",
        uid: member.uid,
        name: member.name,
        phone: member.phone,
        add_date: member.add_date, // 请确保已经格式化为 YYYY-MM-DD
        isPromoterText: member.is_promoter === 1 ? "专家会员" : "标准会员",
        userTypeText: getUserTypeText(member.promoter_type),
        points: member.points,
        tupay: member.tupay,
    });
});

// 抽奖 - 兼容历史调用 - 以后都用event调用
router.get("/lottery", (req, res) => {
    const code = req.query.code || "GFT-2024-05-08";
    res.redirect(`https://totemlife.cn/apps/loyalty/event?code=${code}`);
});

// 赠品 - 兼容历史调用 - 以后都用event调用
router.get("/gift", (req, res) => {
    const code = req.query.code || "GFT-2024-01-26";
    res.redirect(`https://totemlife.cn/apps/loyalty/event?code=${code}`);
});

// 活动入口 - 具体按什么类型处理，是抽奖，还是刮卡在bntLink中配置
router.get('/event', async (req, res) => {
    try {
        const code = req.query.code;
        if (!code) {
            return res.status(400).render('warn', {
                title: '参数错误',
                message: '缺少活动代码',
                description: '请检查活动链接是否完整'
            });
        }

        // 首先尝试从活动表中获取记录
        const [activities] = await rds.query(
            'SELECT * FROM eb_lottery_activities WHERE activity_code = ?',
            [code]
        );

        let template;
        if (activities.length > 0) {
            const activity = activities[0];
            console.log('activity:', activity);
            let config = {};

            try {
                config = JSON.parse(activity.landing_config || '{}');
            } catch (e) {
                logger.error('Error parsing landing_config:', e);
            }

            // 如果配置不为空，使用数据库中的配置
            if (Object.keys(config).length > 0) {
                // 补充必要的字段
                if (!config.title) {
                    config.title = activity.activity_name;
                }

                // 处理开始时间
                if (!config.startTime || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/.test(config.startTime)) {
                    const startDate = new Date(activity.start_time * 1000);
                    config.startTime = startDate.toISOString().slice(0, 19); // 格式化为 YYYY-MM-DDTHH:mm:ss
                }

                // 处理结束时间
                if (!config.stopTime || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/.test(config.stopTime)) {
                    const endDate = new Date(activity.end_time * 1000);
                    config.stopTime = endDate.toISOString().slice(0, 19); // 格式化为 YYYY-MM-DDTHH:mm:ss
                }

                // 处理按钮链接
                if (!config.bntLink) {
                    config.bntLink = `/apps/loyalty/scratch-card/${activity.activity_code}`;
                }

                template = config;
            }
        }
                console.log('template-1:', template);

        // 如果没有找到活动记录或配置为空，则使用 tutils.getSubjectTemplate
        if (!template) {
            template = await tutils.getSubjectTemplate(code);
                console.log('template-2:', template);
        }

        if (!template) {
            return res.status(404).render('warn', {
                title: '未找到活动',
                message: '活动不存在或已结束',
                description: `活动代码: ${code}`
            });
        }

        res.render('loyalty/info', template );
    } catch (error) {
        logger.error('Error in event route:', error);
        res.status(500).render('warn', {
            title: '系统错误',
            message: '获取活动信息失败',
            description: error.message
        });
    }
}); 

router.get("/survey-overwrite", async (req, res) => {
    const uid = req.session.totemUID;
    logger.info(`uid# ${uid} overwrite survey 14784502`);
    //res.redirect(`https://wj.qq.com/s2/14784502/a44e/?uid=${uid}`)
    res.redirect(`https://totemlife.cn/apps/loyalty/survey`);
});

router.get("/survey", async (req, res) => {
    const uid = req.session.totemUID;
    const code = req.query.code || "SURVEY-14784502";
    const template = tutils.getSubjectTemplate(code);
    let {
        tips,
        title,
        background,
        message,
        description,
        comment,
        bntName,
        bntLink,
        bntStyle,
        textStyle,
        counterStyle,
        stopTime,
        startTime,
    } = template;

    const survey_id = code.split("-")?.[1];
    const [rows] = await rds.query(
        `select * from tutem_mall.eb_tupal_survey where action != 'answer.delete' and uid = ? and survey_id = ? order by id desc`,
        [uid, survey_id]
    );
    if (rows.length == 0) {
        //res.redirect(`https://wj.qq.com/s2/${survey_id}/a44e/?uid=${uid}`)
        description = "本期随访已结束";
        bntName = "查看本期结果";
        bntLink = "https://totemlife.cn/apps/loyalty/survey-results/14784502";
        res.render("loyalty/info", {
            background,
            title,
            message,
            description,
            bntName,
            bntLink,
            bntStyle,
            textStyle,
            counterStyle,
            stopTime,
            startTime,
        });
        return;
    } else {
        description = "问卷已提交，金豆已发放";
        bntName = "查看本期结果";
        bntLink = "https://totemlife.cn/apps/loyalty/survey-results/14784502";
    }

    res.render("loyalty/info", {
        background,
        title,
        message,
        description,
        bntName,
        bntLink,
        bntStyle,
        textStyle,
        counterStyle,
        stopTime,
        startTime,
    });
});

router.get("/scratch-card/:activity_code", async (req, res) => {
    try {
        // 步骤1：获取请求参数activity_code，若不存在赋予默认值LTR-2023-09-25
        const { activity_code } = req.params || "LTR-2023-09-25";
        const template = tutils.getSubjectTemplate(activity_code);
        let { background, qrImg } = template;

        // 步骤2：在req.session.user中获得uid，根据uid在members中获得相应的会员记录
        const { uid } = req.session.user;
        const member = await fetchMemberByUid(uid);
        if (!member)
            return res
                .status(404)
                .json({ message: "会员身份识别故障，请联系客服" }); //包括了status == 0的用户

        // 步骤3：根据activity_code获得抽奖活动信息
        const lotteryActivity = await getLotteryActivity(activity_code);

        let activityOnline = false;
        let errMsg = "";
        const currentTime = Math.floor(Date.now() / 1000);
        if (
            currentTime >= lotteryActivity.start_time &&
            currentTime <= lotteryActivity.end_time
        )
            activityOnline = true;

        // 步骤4：通过uid和activity_code查询用户抽奖活动登记表
        let userLotteryRegistration = await getUserLotteryRegistration(
            uid,
            activity_code
        );
        if (!userLotteryRegistration) {
            // 如果登记表中没有记录，则新建一条，remaining_attempts设置为该活动的max_rounds
            const conditions = lotteryActivity.conditions;
            let max_rounds = 0;
            if (eval(conditions)) {
                max_rounds = lotteryActivity.max_rounds;
            } else {
                errMsg = "用户不满足参与活动条件";
            }
            userLotteryRegistration = await createUserLotteryRegistration(
                uid,
                activity_code,
                max_rounds
            );
        }

        // 步骤5：读取活动奖品池数据
        const lotteryPrizes = await getLotteryPrizes(activity_code);

        // 步骤6：查询用户抽奖结果
        const userLotteryResults = await getUserLotteryResults(
            uid,
            activity_code
        );
        const userDrawedCount = userLotteryResults.length;

        // 步骤7：设置默认按钮的显示名称和提示信息
        let defaultMessage = `愿您心想事成、家和人旺`;
        if (currentTime < lotteryActivity.start_time) {
            defaultMessage = "亲爱的，抽奖活动还没有开始";
        } else if (currentTime > lotteryActivity.end_time) {
            defaultMessage = "亲爱的，抽奖活动已经结束了";
        } else if (lotteryPrizes.remaining_quantity < 1) {
            defaultMessage = "亲爱的，抽奖活动奖品已抽完";
        } else if (userLotteryRegistration.remaining_attempts < 1) {
            defaultMessage = "亲爱的，您的抽奖机会已用完";
        }
        const costPoints = lotteryActivity.cost_points;
        const buttonLabel = activityOnline
            ? `点击开始抽奖(每次需${costPoints}金豆)`
            : defaultMessage;

        const rows = await getLotteryResultsByActivityCode(activity_code);
        const totalRecords = rows.length;
        const uniqueUids = new Set(rows.map((row) => row.uid));
        const uniqueUidCount = uniqueUids.size;
        const remainingPrizes = await getRemainingPrizeCount(activity_code);

        const remaining_attempts =
            userLotteryRegistration?.remaining_attempts ?? 0;
        const pointBalance = String(Math.round(member.points));

        res.render("loyalty/scratch-card.hbs", {
            background,
            qrImg,
            uid,
            pointBalance,
            remaining_attempts,
            activityOnline,
            userDrawedCount,
            member,
            totalRecords,
            uniqueUidCount,
            remainingPrizes,
            lotteryActivity,
            lotteryPrizes,
            userLotteryRegistration,
            userLotteryResults,
            buttonLabel,
            defaultMessage,
            errMsg,
        });
    } catch (error) {
        console.error("Error handling scratch-card route:", error);
        res.status(500).json({ message: "Internal Server Error" });
    }
});

router.get("/take-survey/:survey_code", async (req, res) => {
    // 步骤1：获取请求参数survey_code，若不存在赋予默认值LTR-2023-09-25
    const { survey_code } = req.params || "SVY-2024-06-20";
    let background = "https://totemlife.cn/apps/default-image";

    // 步骤2：在req.session.user中获得uid，根据uid在members中获得相应的会员记录
    const { uid } = req.session.user;
    const member = await fetchMemberByUid(uid);
    if (!member)
        return res
            .status(404)
            .json({ message: "会员身份识别故障，请联系客服" }); //包括了status == 0的用户

    // 步骤3：根据survey_code获得贺仪领取活动信息
    const lotteryActivity = await getLotteryActivity(survey_code);
    let surveyTitle = lotteryActivity.activity_name;
    let surveyDescription = lotteryActivity.activity_description;

    let activityOnline = false;

    const currentTime = Math.floor(Date.now() / 1000);
    if (
        currentTime >= lotteryActivity.start_time &&
        currentTime <= lotteryActivity.end_time
    )
        activityOnline = true;

    // 步骤4：通过uid和survey_code查询用户活动结果登记表
    let userLotteryRegistration = await getUserLotteryRegistration(
        uid,
        survey_code
    );
    if (!userLotteryRegistration) {
        // 如果登记表中没有记录，则新建一条，remaining_attempts设置为该活动的max_rounds
        const conditions = lotteryActivity.conditions;
        let max_rounds = 0;
        if (eval(conditions)) max_rounds = lotteryActivity.max_rounds;
        userLotteryRegistration = await createUserLotteryRegistration(
            uid,
            survey_code,
            max_rounds
        );
    }

    // 步骤5：根据用户身份决定其可领取的贺仪内容和选项
    const lotteryPrizes = await getLotteryPrizes(survey_code);

    const gendarOptions = [];
    const ageOptions = [];
    const goodsOptions = [];
    const historyOptions = [];

    gendarOptions.push({ name: "女", description: "女" });
    gendarOptions.push({ name: "男", description: "男" });
    ageOptions.push({
        name: "0 - 婴儿 [0~1岁)",
        description: "0 - 婴儿 [0~1岁)",
    });
    ageOptions.push({
        name: "0 - 婴儿 [0~1岁)",
        description: "0 - 婴儿 [0~1岁)",
    });
    ageOptions.push({
        name: "1 - 幼儿 [1~3岁)",
        description: "1 - 幼儿 [1~3岁)",
    });
    ageOptions.push({
        name: "3 - 儿童 [3~6岁)",
        description: "3 - 儿童 [3~6岁)",
    });
    ageOptions.push({
        name: "6 - 少年 [6~14岁)",
        description: "6 - 少年 [6~14岁)",
    });
    ageOptions.push({
        name: "14 - 青年 [14~28岁)",
        description: "14 - 青年 [14~28岁)",
    });
    ageOptions.push({
        name: "28 - 中年 [28~65岁)",
        description: "28 - 中年 [28~65岁)",
    });
    ageOptions.push({
        name: "65 - 老年 [65岁及以上]",
        description: "65 - 老年 [65岁及以上]",
    });
    historyOptions.push({
        name: "0 - 刚发现确诊未满3个月",
        description: "0 - 刚发现确诊未满3个月",
    });
    historyOptions.push({
        name: "3 - 3个月以上未满六个月",
        description: "3 - 3个月以上未满六个月",
    });
    historyOptions.push({
        name: "6 - 6个月以上未满12个月",
        description: "6 - 6个月以上未满12个月",
    });
    historyOptions.push({
        name: "12 - 12个月以上未满24个月",
        description: "12 - 12个月以上未满24个月",
    });
    historyOptions.push({
        name: "24 - 24个月以上未满36个月",
        description: "24 - 24个月以上未满36个月",
    });
    historyOptions.push({
        name: "36 - 36个月以上",
        description: "36 - 36个月以上",
    });
    goodsOptions.push({ name: "图腾益生", description: "图腾益生" });
    goodsOptions.push({ name: "图腾益生液", description: "图腾益生液" });
    goodsOptions.push({ name: "硫磺菌人参饮", description: "硫磺菌人参饮" });
    goodsOptions.push({ name: "图腾益仙", description: "图腾益仙" });
    goodsOptions.push({ name: "图腾益星", description: "图腾益星" });
    goodsOptions.push({
        name: "图腾贝悦思（原益贝多）",
        description: "图腾贝悦思（原益贝多）",
    });
    goodsOptions.push({
        name: "图腾益和（原益美玑）",
        description: "图腾益和（原益美玑）",
    });
    goodsOptions.push({ name: "图腾益美芭", description: "图腾益美芭" });
    goodsOptions.push({ name: "图腾纾正", description: "图腾纾正" });
    goodsOptions.push({
        name: "图腾纾美（原轻而易简）",
        description: "图腾纾美（原轻而易简）",
    });
    goodsOptions.push({ name: "怡唐舒", description: "怡唐舒" });
    goodsOptions.push({ name: "风之友", description: "风之友" });
    goodsOptions.push({ name: "贝敏菲", description: "贝敏菲" });
    goodsOptions.push({ name: "植精元", description: "植精元" });
    goodsOptions.push({ name: "星悦瞳", description: "星悦瞳" });
    goodsOptions.push({ name: "愈维润", description: "愈维润" });
    goodsOptions.push({ name: "其他", description: "其他" });

    // 步骤6：查询用户问卷提交数量
    const userLotteryResults = await getUserLotteryResults(uid, survey_code);
    const userDrawedCount = userLotteryResults.length;
    const resultTips = "您的问卷已经完成提交，如需帮助请联系您的服务代表";

    // 步骤7：设置默认按钮的显示名称和提示信息
    let defaultMessage = `愿您心想事成家和人旺`;
    if (currentTime < lotteryActivity.start_time) {
        defaultMessage = "讲座问题还未开始征集";
    } else if (currentTime > lotteryActivity.end_time) {
        defaultMessage = "讲座问题已经截止收集";
    } else if (lotteryPrizes.remaining_quantity < 1) {
        defaultMessage = "提问抽奖奖品已被领完";
    } else if (userLotteryRegistration.remaining_attempts < 1) {
        defaultMessage = "您的提问次数已经用完";
    }
    const buttonLabel = activityOnline ? `提交问题并抽取奖品` : defaultMessage;

    const rows = await getLotteryResultsByActivityCode(survey_code);
    const totalRecords = rows.length;
    const uniqueUids = new Set(rows.map((row) => row.uid));
    const uniqueUidCount = uniqueUids.size;
    const remainingPrizes = await getRemainingPrizeCount(survey_code);

    const remaining_attempts = userLotteryRegistration?.remaining_attempts ?? 0;
    const tupayBalance = String(Math.round(member.now_money));

    res.render("loyalty/take-survey.hbs", {
        background,
        uid,
        tupayBalance,
        remaining_attempts,
        activityOnline,
        userDrawedCount,
        member,
        totalRecords,
        uniqueUidCount,
        remainingPrizes,
        lotteryActivity,
        lotteryPrizes,
        surveyTitle,
        surveyDescription,
        gendarOptions,
        ageOptions,
        historyOptions,
        goodsOptions,
        userLotteryRegistration,
        userLotteryResults,
        buttonLabel,
        defaultMessage,
        resultTips,
    });
});

router.get("/choose-gift/:activity_code", async (req, res) => {
    try {
        // 步骤1：获取请求参数activity_code，若不存在赋予默认值LTR-2023-09-25
        const { activity_code } = req.params || "GFT-2024-01-26";
        const template = tutils.getSubjectTemplate(activity_code);
        //let { background } = template;
        let background = "https://totemlife.cn/apps/default-image";

        // 步骤2：在req.session.user中获得uid，根据uid在members中获得相应的会员记录
        const { uid } = req.session.user;
        const member = await fetchMemberByUid(uid);
        if (!member)
            return res
                .status(404)
                .json({ message: "会员身份识别故障，请联系客服" }); //包括了status == 0的用户

        // 步骤3：根据activity_code获得贺仪领取活动信息
        const lotteryActivity = await getLotteryActivity(activity_code);

        let activityOnline = false;

        const currentTime = Math.floor(Date.now() / 1000);
        if (
            currentTime >= lotteryActivity.start_time &&
            currentTime <= lotteryActivity.end_time
        )
            activityOnline = true;

        // 步骤4：通过uid和activity_code查询用户贺仪领取活动登记表
        let userLotteryRegistration = await getUserLotteryRegistration(
            uid,
            activity_code
        );
        if (!userLotteryRegistration) {
            // 如果登记表中没有记录，则新建一条，remaining_attempts设置为该活动的max_rounds
            const conditions = lotteryActivity.conditions;
            let max_rounds = 0;
            if (eval(conditions)) max_rounds = lotteryActivity.max_rounds;
            userLotteryRegistration = await createUserLotteryRegistration(
                uid,
                activity_code,
                max_rounds
            );
        }

        // 步骤5：根据用户身份决定其可领取的贺仪内容和选项
        const lotteryPrizes = await getLotteryPrizes(activity_code);
        const giftOptions = [];
        const addonOptions = [];
        let giftDescription = `您不适用此项目，请咨询图腾生命医学助理了解更多。`;
        let greetingTitle = "图腾生命医学，以礼存心";
        if (
            member.promoter_type > 0 &&
            member.status == 1 &&
            member.promoter_type == 3
        ) {
            greetingTitle = "开工揭语，试试手气";
            giftOptions.push({
                name: "TUPAY-202.40",
                description: "202.4图贝-可直接使用",
            });
            giftDescription = `
            1、公司节庆赠送给员工账号的图贝，可在图腾生命医学小程序直接购买产品使用<br>
            2、可与积分、员工折扣等同时使用，无有效期<br>
            <br>当前图贝余额：${member.now_money}<br>
            `;
        } else {
            activityOnline = false;
            await task.notifyXiaoteng(
                199999,
                `[WARNING] Unqualified UID#${uid} accessed ${activity_code} `
            );
        }

        // 步骤6：查询用户贺仪领取结果
        const userLotteryResults = await getUserLotteryResults(
            uid,
            activity_code
        );
        const userDrawedCount = userLotteryResults.length;
        const resultTips =
            "您的贺仪领取已完成登记，如需帮助请联系您的服务代表或图腾生命医学助理";

        // 步骤7：设置默认按钮的显示名称和提示信息
        let defaultMessage = `愿您心想事成、家和人旺`;
        if (currentTime < lotteryActivity.start_time) {
            defaultMessage = "贺仪领取活动还没有开始";
        } else if (currentTime > lotteryActivity.end_time) {
            defaultMessage = "贺仪领取活动已经结束了";
        } else if (lotteryPrizes.remaining_quantity < 1) {
            defaultMessage = "贺仪活动赠品已被领完";
        } else if (userLotteryRegistration.remaining_attempts < 1) {
            defaultMessage = "您的贺仪领取次数已用完";
        }
        const buttonLabel = activityOnline
            ? `点击登记领取贺仪`
            : defaultMessage;

        const rows = await getLotteryResultsByActivityCode(activity_code);
        const totalRecords = rows.length;
        const uniqueUids = new Set(rows.map((row) => row.uid));
        const uniqueUidCount = uniqueUids.size;
        const remainingPrizes = await getRemainingPrizeCount(activity_code);

        const remaining_attempts =
            userLotteryRegistration?.remaining_attempts ?? 0;
        const tupayBalance = String(Math.round(member.now_money));

        res.render("loyalty/choose-gift.hbs", {
            background,
            uid,
            tupayBalance,
            remaining_attempts,
            activityOnline,
            userDrawedCount,
            member,
            totalRecords,
            uniqueUidCount,
            remainingPrizes,
            lotteryActivity,
            lotteryPrizes,
            greetingTitle,
            giftDescription,
            giftOptions,
            addonOptions,
            userLotteryRegistration,
            userLotteryResults,
            buttonLabel,
            defaultMessage,
            resultTips,
        });
    } catch (error) {
        console.error("Error handling choose-gift route:", error);
        res.status(500).json({ message: "Internal Server Error" });
    }
});

// 处理用户点击抽奖按钮的路由
router.post("/scratch-card/:activity_code", async (req, res) => {
    try {
        const { uid } = req.session.user;
        const { activity_code } = req.params;

        // 在剩余奖池中随机抽取1项奖品，记录用户抽奖结果
        let lotteryResult = await drawLottery(uid, activity_code);

        // 检查是否无法抽奖
        if (lotteryResult.unableToDraw) {
            return res.json({
                unableToDraw: true,
                message: "抽奖活动次数已经用完",
            });
        }

        const prize_id = lotteryResult.prize_id;
        const lottery_id = lotteryResult.id; // 保存抽奖记录ID

        if (prize_id == 31) {
            const tubay = 202.4;
            const link_id = `GFT-2024-02-18`;
            const name = "领取图腾生命医学甲辰年开工利是获赠";
            const title = `${link_id} ${name}`;
            const mark = `${link_id} ${name}`;
            const result = await tutils.grantTubay(
                uid,
                link_id,
                title,
                tubay,
                mark
            );
            lotteryResult.tips =
                result.errcode == 0
                    ? "202.40图贝已发放，可在小程序个人中心查看使用"
                    : result.errmsg;
        } else {
            // 获取奖品和活动信息
            const [prizes] = await rds.query(
                `SELECT p.*, a.activity_name, a.cost_points 
                FROM tutem_mall.eb_lottery_prizes p 
                JOIN tutem_mall.eb_lottery_activities a ON p.activity_code = a.activity_code 
                WHERE p.prize_id = ? AND p.activity_code = ?`,
                [prize_id, activity_code]
            );

            if (!prizes.length) {
                return res.json({
                    success: false,
                    message: '奖品不存在'
                });
            }

            const prize = prizes[0];
            const {
                activity_name,
                prize_name,
                prize_tips,
                auto_grant_type,
                grant_options,
                cost_points
            } = prize;

            // 更新 lotteryResult，但保留 id
            lotteryResult = {
                ...lotteryResult,  // 保留原有信息，包括 id
                tips: prize_tips || ''
            };

            // 扣除抽奖消耗的金豆
            if (cost_points > 0) {
                const costLinkId = `user-lottery-cost-${lottery_id}`; // 使用保存的 lottery_id
                const costResult = await tutils.grantPoints(
                    uid,
                    costLinkId,
                    `${activity_code} 抽奖消耗`,
                    -cost_points,
                    `${activity_code} ${activity_name} 抽奖消耗`
                );

                if (costResult.errcode !== 0) {
                    return res.json({
                        success: false,
                        message: costResult.errmsg
                    });
                }
            }

            // 根据自动发放类型处理奖品
            if (auto_grant_type > 0) {
                const options = typeof grant_options === 'string' 
                    ? JSON.parse(grant_options) 
                    : grant_options;

                if (auto_grant_type === 1 && options.points) {
                    // 发放金豆
                    const link_id = `user-lottery-${lottery_id}-prize-${prize_id}`; // 使用保存的 lottery_id
                    const result = await tutils.grantPoints(
                        uid,
                        link_id,
                        `${activity_code} ${activity_name}`,
                        options.points,
                        `${activity_code} ${activity_name} 奖品: ${prize_name}`
                    );

                    lotteryResult.tips = result.errcode === 0
                        ? `${options.points}金豆已发放，可在小程序个人中心查看使用`
                        : result.errmsg;

                    const notice = `【金豆奖励】UID#${uid} 通过${activity_code} ${link_id} 获得 #${prize_id} ${prize_name}`;
                    await task.notifyWework(1, notice, 1000026);
                }
                else if (auto_grant_type === 2 && options.coupon_id) {
                    // 发放优惠券
                    const result = await tutils.grantCoupon(uid, options.coupon_id, activity_code);

                    lotteryResult.tips = result.errcode === 0
                        ? '优惠券已发放，可在小程序个人中心查看使用'
                        : result.errmsg;

                    if (result.errcode === 0) {
                        const notice = `【礼券奖励】UID#${uid} 通过${activity_code} lottery-${lottery_id} 获得 #${prize_id} ${prize_name}`;
                        await task.notifyWework(1, notice, 1000026);
                    }
                }
            }
        }

        // 返回结果
        res.json({
            success: true,
            data: lotteryResult
        });

    } catch (error) {
        logger.error("Error in scratch-card:", error);
        res.status(500).json({
            success: false,
            message: error.message || "处理抽奖请求失败"
        });
    }
});

// 处理用户点击抽奖按钮的路由
router.post("/take-survey/:activity_code", async (req, res) => {
    const { uid } = req.session.user;
    const { activity_code } = req.params;
    const lotteryActivity = await getLotteryActivity(activity_code);
    const activity_name = lotteryActivity.activity_name;

    const {
        age,
        gendar,
        history,
        diagnosis,
        hospital,
        therapy,
        goods,
        question,
    } = req.body;
    const payload = req.body;
    const action = "answer.create";
    const now = Math.floor(Date.now() / 1000); // MySQL 时间戳
    const answers = tutils.generatePayloadText(payload);

    const sql = `INSERT INTO tutem_mall.eb_tupal_survey (uid, action, survey_id, payload, answers, answers_json, add_time) VALUES (?, ?, ?, ?, ?, ?, ?)`;
    const [rows] = await rds.query(sql, [
        uid,
        action,
        activity_code,
        JSON.stringify(payload),
        answers,
        JSON.stringify(payload),
        now,
    ]);

    // 记录用户领奖结果：对于只有一个奖品的活动，随机就是唯一
    let lotteryResult = await drawLottery(uid, activity_code);
    // 检查是否无法领奖
    if (lotteryResult.unableToDraw) {
        return res.json({ unableToDraw: true, message: "抽奖次数已经用完" });
    }

    lotteryResult.tips = "答案已收到！";

    const { id, prize_id, prize_name } = lotteryResult;
    const updateMemo = `UPDATE eb_user_lottery_results SET memo = '${answers}' WHERE id = ${id} and uid = ${uid}`;
    await rds.query(updateMemo);

    if (prize_id == 40) {
        const link_id = `user-lottery-${id}-prize-${prize_id}`;
        const points = 500;
        const title = `${activity_code} ${activity_name}`;
        const mark = `${activity_code} ${activity_name}`;
        const result = await tutils.grantPoints(
            uid,
            link_id,
            title,
            points,
            mark
        ); //因为有link_id，所以可以保证不会重复提交
        lotteryResult.tips =
            result.errcode == 0
                ? `${points}金豆已发放，可在小程序个人中心查看使用`
                : result.errmsg;
        const notice = `【金豆奖励】UID#${uid} 通过${activity_code} ${link_id} 获得 #${prize_id} ${prize_name}`;
        await task.notifyWework(1, notice, 1000026);
    }

    if (prize_id == 41 || prize_id == 42 || prize_id == 43) {
        const link_id = `user-lottery-${id}-prize-${prize_id}`;
        const title = `${activity_code} ${activity_name}`;
        const mark = `${activity_code} ${activity_name}`;
        const notice = `【其它奖励】UID#${uid} 通过${activity_code} ${link_id} 获得 #${prize_id} ${prize_name}`;
        lotteryResult.tips = notice;
        await task.notifyWework(1, notice, 1000026);
    }

    const notice = `U#${uid} 提交了 ${activity_code} 问卷\n${answers}\n [所有问卷](https://totemlife.cn/apps/loyalty/lottery-result/${activity_code})`;
    await task.notifyWework(1, notice, 1000026);

    // 返回用户抽奖结果
    res.json(lotteryResult);
});

// 处理用户点击抽奖按钮的路由
router.post("/choose-gift/:activity_code", async (req, res) => {
    try {
        const { uid } = req.session.user;
        const { activity_code } = req.params;
        const { selectedGift, memo } = req.body;

        // 记录用户领奖结果：对于只有一个奖品的活动，随机就是唯一
        let lotteryResult = await drawLottery(uid, activity_code);
        // 检查是否无法领奖
        if (lotteryResult.unableToDraw) {
            return res.json({
                unableToDraw: true,
                message: "领奖活动次数已经用完",
            });
        }
        const prize_id = lotteryResult.prize_id;
        const prize_name = lotteryResult.prize_name;

        if (prize_id == 31) {
            const tubay = 202.4;
            const link_id = `user-lottery-id-${lotteryResult.id}`;
            const name = "领取图腾生命医学甲辰年开工利是获赠";
            const title = `${link_id} ${name}`;
            const mark = `${link_id} ${name}`;
            const result = await tutils.grantTubay(
                uid,
                link_id,
                title,
                tubay,
                mark
            );
            const updateMemo = `UPDATE eb_user_lottery_results SET memo = '${memo}' WHERE id = ${lotteryResult.id} and uid = ${uid}`;
            await rds.query(updateMemo);
            lotteryResult.tips =
                result.errcode == 0
                    ? "202.40图贝已发放，可在小程序个人中心查看使用"
                    : result.errmsg;
            const notice = `【图贝奖励】UID#${uid} 通过${activity_code} ${link_id} 获得 #${prize_id} ${prize_name} | ${memo}`;
            await task.notifyWework(1, notice, 1000026);
        }

        // 返回用户抽奖结果
        res.json(lotteryResult);
    } catch (error) {
        console.error("Error handling choose-gift POST route:", error);
        res.status(500).json({ message: "Internal Server Error" });
    }
});

// 获取抽奖活动信息
async function getLotteryActivity(activity_code) {
    const [rows] = await rds.query(
        "SELECT * FROM eb_lottery_activities WHERE activity_code = ?",
        [activity_code]
    );
    if (rows.length > 0) {
        return rows[0];
    } else {
        throw new Error("抽奖活动不存在");
    }
}

// 获取活动奖品池数据
async function getLotteryPrizes(activity_code) {
    const [rows] = await rds.query(
        "SELECT * FROM eb_lottery_prizes WHERE activity_code = ?",
        [activity_code]
    );
    return rows;
}

// 获取用户抽奖活动登记信息
async function getUserLotteryRegistration(uid, activity_code) {
    const [rows] = await rds.query(
        "SELECT * FROM eb_user_lottery_registration WHERE uid = ? AND activity_code = ?",
        [uid, activity_code]
    );
    if (rows.length > 0) {
        return rows[0];
    } else {
        return null;
    }
}

// 创建用户抽奖活动登记信息
async function createUserLotteryRegistration(uid, activity_code, max_rounds) {
    const add_time = Math.floor(Date.now() / 1000);
    const insertQuery =
        "INSERT INTO eb_user_lottery_registration (uid, activity_code, remaining_attempts, add_time) VALUES (?, ?, ?, ?)";
    const values = [uid, activity_code, max_rounds, add_time];
    const [result] = await rds.query(insertQuery, values);
    return {
        id: result.insertId,
        uid,
        activity_code,
        remaining_attempts: max_rounds,
        add_time,
    };
}

// 获取用户抽奖结果
async function getUserLotteryResults(uid, activity_code) {
    const [rows] = await rds.query(
        "SELECT r.*, p.prize_tips as prize_tips, DATE_FORMAT(FROM_UNIXTIME(r.add_time), '%Y-%m-%d %H:%i:%s') AS added_at FROM eb_user_lottery_results r left join eb_lottery_prizes p on (r.prize_id = p.prize_id) WHERE r.uid = ? AND r.prize_id in ( select prize_id from eb_lottery_prizes where activity_code = ? ) ORDER BY add_time DESC",
        [uid, activity_code]
    );
    return rows;
}

// 执行抽奖操作
async function drawLottery(uid, activity_code) {
    const add_time = Math.floor(Date.now() / 1000);

    // 更新用户抽奖活动登记信息，减少剩余尝试次数
    const updateAttemptsQuery =
        "UPDATE eb_user_lottery_registration SET remaining_attempts = remaining_attempts - 1 WHERE uid = ? AND activity_code = ? AND remaining_attempts > 0";
    const updateAttemptsValues = [uid, activity_code];
    const [updateResult] = await rds.query(
        updateAttemptsQuery,
        updateAttemptsValues
    );

    // 检查剩余抽奖次数是否大于零
    if (updateResult.affectedRows === 0) {
        // 如果剩余次数不足，则返回一个标识表示无法抽奖
        return { unableToDraw: true };
    }

    // 实现抽奖逻辑，从奖品池中随机抽取奖品
    // 假设你有一个函数 drawRandomPrize() 来完成这个操作
    const randomPrize = await drawRandomPrize(activity_code);

    // 记录用户抽奖结果
    const insertQuery =
        "INSERT INTO eb_user_lottery_results (uid, prize_id, prize_name, lottery_time, processing_status, add_time) VALUES (?, ?, ?, ?, ?, ?)";
    const values = [
        uid,
        randomPrize.prize_id,
        randomPrize.prize_name,
        add_time,
        0,
        add_time,
    ];
    const [result] = await rds.query(insertQuery, values);

    // 返回用户抽奖结果
    return {
        id: result.insertId,
        uid,
        prize_id: randomPrize.prize_id,
        prize_name: randomPrize.prize_name,
        lottery_time: add_time,
        processing_status: 0,
        add_time,
    };
}

// 实现随机抽奖逻辑
async function drawRandomPrize(activity_code) {
    // 查询奖品池中剩余奖品数量不为0的奖品
    const [rows] = await rds.query(
        "SELECT * FROM eb_lottery_prizes WHERE activity_code = ? AND remaining_quantity > 0",
        [activity_code]
    );

    if (rows.length === 0) {
        throw new Error("活动奖品已抽完");
    }

    // 随机选择一个奖品
    // const randomIndex = Math.floor(Math.random() * rows.length);
    // const randomPrize = rows[randomIndex];

    // 计算总权重，即所有剩余奖品数量的总和
    let totalWeight = 0;
    for (const prize of rows) {
        totalWeight += prize.remaining_quantity;
    }

    // 随机选择一个奖品，根据权重分配几率
    let randomWeight = Math.floor(Math.random() * totalWeight);
    let selectedPrize = null;

    for (const prize of rows) {
        randomWeight -= prize.remaining_quantity;
        if (randomWeight <= 0) {
            selectedPrize = prize;
            break;
        }
    }

    // 更新奖品池中的剩余数量
    await rds.query(
        "UPDATE eb_lottery_prizes SET remaining_quantity = remaining_quantity - 1 WHERE prize_id = ?",
        [selectedPrize.prize_id]
    );

    return selectedPrize;
}

// 创建用于列出抽奖结果的路由
router.get("/lottery-result/:activity_code", async (req, res) => {
    const { activity_code } = req.params;

    try {
        // 在此处查询特定抽奖活动的所有抽奖结果
        const lotteryResults =
            await getLotteryResultsByActivityCode(activity_code);

        const sql = `SELECT r.uid, u.real_name as name, u.promoter_type as type, u.rep_code, u.phone, r.prize_name as prize, r.memo, r.comment, DATE_FORMAT(FROM_UNIXTIME(r.lottery_time), '%Y-%m-%d %H:%i:%s') AS drawed_at from eb_user_lottery_results r left join eb_user u on (r.uid = u.uid) WHERE prize_id in ( select prize_id from eb_lottery_prizes where activity_code = '${activity_code}' ) order by r.prize_id asc, rep_code asc, id desc`;
        const downloadLink =
            req.session.crmROLE == "crm-admin" ||
            req.session.crmROLE == "crm-gmoffc"
                ? `
            <span><a href="https://totemlife.cn/apps/download-excel?sql=${encodeURIComponent(sql)}&filename=${activity_code}-report.xls"><span class="fas fa-download"></i></a></span>
        `
                : "";

        // 渲染列出抽奖结果的页面，并将数据传递给模板
        res.render("loyalty/lottery-results", { lotteryResults, downloadLink });
    } catch (error) {
        console.error("Error fetching lottery results:", error);
        res.status(500).json({ message: "Internal Server Error" });
    }
});

router.get("/mtx-refer-details", async (req, res) => {
    let {
        slug = "caae-using-gut-microbiota-to-treat-epilepsy-china-is-bending-the-curve",
    } = req.params;
    //slug= 'first-report-of-single-strain-bf839';

    let sql = `select a.id, concat('#', a.peer_uid, ' ', su.real_name, ' T', su.promoter_type) as sharer, concat('#', a.uid, ' ', ru.real_name, ' T', ru.promoter_type) as reader, from_unixtime(a.add_time) as read_time, a.options, a.path from tutem_mall.eb_user_action a left join tutem_mall.eb_user su on (a.peer_uid = su.uid) left join tutem_mall.eb_user ru on (a.uid = ru.uid) where action = 'mta-refer' and path like '%${slug}%' order by id desc;`;

    const downloadLink =
        req.session.crmROLE == "crm-admin" ||
        req.session.crmROLE == "crm-gmoffc"
            ? `
        <span><a href="https://totemlife.cn/apps/download-excel?sql=${encodeURIComponent(sql)}&filename=${slug}-report.xls"><span class="fas fa-download"></i></a></span>
    `
            : "";

    const [rows] = await rds.query(sql);
    const fields = ["id", "转发者", "阅读者", "阅读时间", "选项", "内容地址"];
    res.render("results", { fields, rows, downloadLink, subTitle: slug });
});

//合法形式为类似 ccc f uuu v 其中ccc为活动id uuu 为用户ID f|v为固定字符, v需要校验
router.get("/blessing/:code", async (req, res) => {
    const code = req.params.code;
    const matches = code.match(/(\d+)f(\d+)/);
    let from_uid = 0;
    let compaign_id = 0;

    // 解析路由参数获取 compaign_id 和 from_uid
    if (matches && matches.length === 3) {
        const [, cStr, fStr] = matches;
        // 确保 from_uid 和 compaign_id 都是有效的数字字符串
        if (!isNaN(parseInt(fStr)) && !isNaN(parseInt(cStr))) {
            from_uid = parseInt(fStr);
            compaign_id = parseInt(cStr);
        }
    }
    const visit_uid = req.session.totemUID; // 假设 session 中有 totemUID
    return res.json({ compaign_id, from_uid, visit_uid });
});

//原先设计是允许用户使用图贝支付，为兼容和查询用而保留
router.get("/enable-tupay", async (req, res) => {
    const { totemUID } = req.session; // 获取用户的totemUID
    if (!totemUID) {
        return res.status(400).json({ error: "No totemUID provided" });
    }
    const [rows] = await rds.query(
        `SELECT DATE_FORMAT(NOW(), '%Y-%m-%d %H:%i:%s') AS time, uid, now_money as tubay, roles FROM tutem_mall.eb_user WHERE uid = ?`,
        [totemUID]
    );
    const row = rows[0];
    return res.render("warn", {
        title: "欢迎来到营养微生态医学最前沿",
        message: "患者的笑容是我们最好的回报",
        description: `#${row.uid} ${row.roles} ${row.tubay}`,
        icon: "weui-icon-success weui-icon_msg",
    });
});

// 实现获取特定抽奖活动的抽奖结果的函数
async function getLotteryResultsByActivityCode(activityCode) {
    try {
        const [rows] = await rds.query(
            `SELECT r.uid, u.real_name as name, u.promoter_type as type, u.rep_code, u.phone, r.prize_name as prize, r.memo, r.comment, DATE_FORMAT(FROM_UNIXTIME(r.lottery_time), '%Y-%m-%d %H:%i:%s') AS drawed_at from eb_user_lottery_results r left join eb_user u on (r.uid = u.uid) WHERE prize_id in ( select prize_id from eb_lottery_prizes where activity_code = '${activityCode}' ) order by r.prize_id asc, rep_code asc, id desc`
        );

        const mRows = rows.map((row) => {
            const modifiedPhone = row.phone
                ? "***" + row.phone.slice(7)
                : row.phone;
            return { ...row, phone: modifiedPhone };
        });
        return mRows;
    } catch (error) {
        throw error;
    }
}

async function getRemainingPrizeCount(activityCode) {
    // 构建 SQL 查询语句
    const sql = `SELECT SUM(remaining_quantity) AS totalRemaining FROM eb_lottery_prizes WHERE activity_code = ?`;
    const [rows] = await rds.query(sql, [activityCode]);
    const totalRemaining = rows[0].totalRemaining;
    return totalRemaining;
}

// 会议列表相关路由
router.get('/conference/list', async (req, res) => {
    const conferences = Object.values(conferenceData).map((conf) => ({
        conference_code: conf.conference_code,
        conference_name: conf.conference_name,
        conference_date: conf.conference_date,
        conference_time: conf.conference_time,
        location: conf.location,
        materials_url: conf.materials_url,
        replay_url: conf.replay_url,
        description: conf.description,
        status: conf.status,
        tags: conf.tags,
        cover_image: conf.cover_image,
        speakers_count: conf.speakers.length,
        contacts: conf.contacts,
        contacts_count: conf.contacts ? conf.contacts.length : 0
    }));

    res.render("loyalty/conference/list", {
        title: "会议资料列表",
        conferences: conferences,
    });
});

router.get('/conference/:code/materials', async (req, res) => {
    const { code } = req.params;
    const conference = conferenceData[code];

    if (!conference) {
        return res.status(404).render("warn", {
            title: "未找到会议",
            message: "该会议资料不存在",
            description: `会议代码: ${code}`,
            icon: "weui-icon-warn weui-icon_msg",
        });
    }

    res.render("loyalty/conference/materials", {
        title: "会议资料包",
        conference: conference,
    });
});

// 用户访问问卷路由
router.get('/survey/:program_code', async (req, res) => {
    try {
        const { program_code } = req.params;
        const uid = req.session.totemUID;

        // 获取问卷信息
        const [surveys] = await rds.query(
            'SELECT * FROM eb_survey_list WHERE program_code = ?',
            [program_code]
        );

        if (surveys.length === 0) {
            return res.render('warn', {
                title: '问卷不存在',
                message: '您访问的问卷不存在',
                description: '请检查问卷链接是否正确',
                icon: 'weui-icon-warn weui-icon_msg'
            });
        }

        const survey = surveys[0];

        // 检查问卷是否开放访问
        if (survey.status !== 'OPEN') {
            return res.render('warn', {
                title: '问卷已关闭',
                message: '该问卷已停止访问',
                description: survey.description || '感谢您的关注',
                icon: 'weui-icon-warn weui-icon_msg'
            });
        }

        // 获取用户信息并检查合格条件
        const [users] = await rds.query(
            'SELECT * FROM tutem_mall.eb_user WHERE uid = ?',
            [uid]
        );

        if (users.length === 0) {
            return res.render('warn', {
                title: '用户未登录',
                message: '请先登录后再访问问卷',
                description: '您可以通过图腾生命医学小程序登录',
                icon: 'weui-icon-warn weui-icon_msg'
            });
        }

        const u = users[0];
        if (!eval(survey.conditions)) {
            return res.render('warn', {
                title: '不符合参与条件',
                message: '您暂时不符合参与条件',
                description: survey.description || '感谢您的关注',
                icon: 'weui-icon-warn weui-icon_msg'
            });
        }

        // 符合所有条件，跳转到问卷入口
        res.redirect(survey.entry_url);
    } catch (error) {
        logger.error('Error accessing survey:', error);
        res.status(500).render('warn', {
            title: '系统错误',
            message: '访问问卷失败',
            description: error.message,
            icon: 'weui-icon-warn weui-icon_msg'
        });
    }
});

// 添加重定向到新的管理模块
router.get('/admin', (req, res) => {
    res.redirect(`/apps/admin`);
});
router.get('/admin/*', (req, res) => {
    const newPath = req.path.replace('/loyalty/admin', '/admin');
    res.redirect(`/apps${newPath}`);
});

module.exports = router;
